package com.ruoyi.framework.config.redis;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author cql
 * <p>
 * springboot-cache 整合redis
 * 1. 引入redis的依赖spring-boot-starter-data-redis
 * 2. 配置文件中配置redis的相关配置
 * 3.开启缓存功能 @EnableCaching
 * 4.我们就可以使用了
 */

/**
 * springboot-cache 整合redis
 * 1. 引入redis的依赖spring-boot-starter-data-redis
 * 2. 配置文件中配置redis的相关配置
 * 3.开启缓存功能 @EnableCaching
 * 4.我们就可以使用了
 */

/**
 * 新版本似乎不用再这样
 */
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        /**
         * 改变redis的序列化
         */
        /**
         * key使用string序列化器
         */
        config = config.serializeKeysWith(
                RedisSerializationContext.
                SerializationPair.
                fromSerializer(new StringRedisSerializer()));
        /**
         * value:使用我们自定义的序列化器
         */
        config = config.serializeValuesWith(RedisSerializationContext.
                SerializationPair.
                fromSerializer(new FastJson2JsonRedisSerializer(Object.class)));


        /**
         * 将配置文件中的所有配置生效
         */
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }

}
